package org.beetl.sql.springboot.conf;


import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.sql.core.engine.template.BeetlTemplateEngine;
import org.beetl.sql.springboot.Db;
import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.ext.DBInitHelper;
import org.beetl.sql.starter.SQLManagerCustomize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@Configuration
public class DatasourceConfig {
	@Autowired
	ApplicationContext ctx;

	@Bean(name = "ds")
	public DataSource datasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		ds.setMaximumPoolSize(2);
		return ds;
	}

	@Bean
	public SQLManagerCustomize tableTenantSQLManagerCustomize() {
		return new SQLManagerCustomize() {
			@Override
			public void customize(String sqlMangerName, SQLManager manager) {
				DBInitHelper.executeSqlScript(manager, "db/schema.sql");
				//表${toTable('order_log')}是个虚拟的，数据库定义来自order_log,必须放到metadata加载前
				manager.addVirtualTable("order_log","${toTable('order_log')}");
				manager.refresh();

				BeetlTemplateEngine templateEngine = (BeetlTemplateEngine)manager.getSqlTemplateEngine();
				//表${toTable('order_log')}是个虚拟的，数据库定义来自order_log
				manager.addVirtualTable("order_log","${toTable('order_log')}");
				// 注册一个方法来实现映射到多表的逻辑
				templateEngine.getBeetl().getGroupTemplate().registerFunction("toTable", new Function(){
					@Override
					public Object call(Object[] paras, Context ctx) {
						String tableName = (String)paras[0];
						//租户表
						return tableName+"_"+Db.localValue.get();

					}
				});

			}
		};

	}
}
